package com.study.juc.lk;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @program: juc-study
 * @author: jzhou
 * @date: 2022-08-25 10:00
 * @version: 1.0
 * @description: 线程间的通信
 * 案例：有两个线程
 * 第一个线程 当数字为 0 时 实现 +1 操作 其他时间则等待
 * 第二个线程 当数字不为 0 时 实现 -1 操作， 其他时间则等待
 *
 **/
public class ThreadSignalingDemo {
	public static void main(String[] args) {
		MyNumber myNumber = new MyNumber();

		new Thread(()->{
			for (int i = 0; i < 10; i++) {
				try {
					myNumber.increment();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		},"AA").start();

		new Thread(()->{
			for (int i = 0; i < 10; i++) {
				try {
					myNumber.increment();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		},"CC").start();


		new Thread(()->{
			for (int i = 0; i < 10; i++) {
				try {
					myNumber.decrement();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		},"BB").start();



		new Thread(()->{
			for (int i = 0; i < 10; i++) {
				try {
					myNumber.decrement();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		},"DD").start();

	}
}

class MyNumber{
	private int number = 0;
	private final Lock lock = new ReentrantLock();
	private final Condition condition  = lock.newCondition();

	public int getNumber() {
		return number;
	}

	public void increment() throws InterruptedException {
		lock.lock();
		while (number != 0){
			condition.await();
//			this.wait();
		}

		try {
			number++;
			System.out.println(Thread.currentThread().getName() +"\t"+ number);
			condition.signalAll();
		}finally {
			lock.unlock();
		}
	}

	public void decrement() throws InterruptedException {

		lock.lock();
		while (number != 1){
			condition.await();// 调用它的前提是当前线程占有锁 否则将会出现 IllegalMonitorStateException
		}
		try {
			number--;
			System.out.println(Thread.currentThread().getName() +"\t"+ number);
			condition.signalAll();
		}finally {
			lock.unlock();
		}
	}
}
